package com.lp.guoguo.common.utils;

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.properties.TextAlignment;
import com.itextpdf.layout.properties.UnitValue;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.util.List;

@Slf4j
public class PdfUtils {

    /**
     * 生成简单的PDF文档
     * @param title 标题
     * @param content 内容
     * @return PDF文件字节数组
     */
    public static byte[] generateSimplePdf(String title, String content) {
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            PdfWriter writer = new PdfWriter(baos);
            PdfDocument pdf = new PdfDocument(writer);
            Document document = new Document(pdf);

            // 添加标题
            Paragraph titleParagraph = new Paragraph(title)
                    .setTextAlignment(TextAlignment.CENTER)
                    .setFontSize(20);
            document.add(titleParagraph);

            // 添加内容
            Paragraph contentParagraph = new Paragraph(content)
                    .setTextAlignment(TextAlignment.LEFT)
                    .setFontSize(12);
            document.add(contentParagraph);

            document.close();
            return baos.toByteArray();
        } catch (Exception e) {
            log.error("PDF生成失败", e);
            return null;
        }
    }

    /**
     * 生成表格PDF
     * @param title 标题
     * @param headers 表头
     * @param data 数据
     * @return PDF文件字节数组
     */
    public static byte[] generateTablePdf(String title, String[] headers, List<String[]> data) {
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            PdfWriter writer = new PdfWriter(baos);
            PdfDocument pdf = new PdfDocument(writer);
            Document document = new Document(pdf);

            // 添加标题
            Paragraph titleParagraph = new Paragraph(title)
                    .setTextAlignment(TextAlignment.CENTER)
                    .setFontSize(20);
            document.add(titleParagraph);

            // 创建表格
            Table table = new Table(UnitValue.createPercentArray(headers.length));
            
            // 添加表头
            for (String header : headers) {
                table.addHeaderCell(header);
            }

            // 添加数据
            for (String[] row : data) {
                for (String cell : row) {
                    table.addCell(cell);
                }
            }

            document.add(table);
            document.close();
            return baos.toByteArray();
        } catch (Exception e) {
            log.error("PDF生成失败", e);
            return null;
        }
    }
} 